// @APIVersion 1.0.0
// @Title beego Test API
// @Description beego has a very cool tools to autogenerate documents for your API
// @Contact astaxie@gmail.com
// @TermsOfServiceUrl http://beego.me/
// @License Apache 2.0
// @LicenseUrl http://www.apache.org/licenses/LICENSE-2.0.html
package routers

import (
	"coinsend/controllers"

	"coinsend/models"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/context"
	"github.com/astaxie/beego/plugins/cors"
)

func init() {

	// 这段代码放在router.go文件的init()的开头
	beego.InsertFilter("*", beego.BeforeRouter, cors.Allow(&cors.Options{
		AllowAllOrigins:  true,
		AllowMethods:     []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
		AllowHeaders:     []string{"Origin", "Authorization", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type"},
		ExposeHeaders:    []string{"Content-Length", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type"},
		AllowCredentials: true,
	}))
	ns := beego.NewNamespace("/v1",
		beego.NSBefore(jwtAuth),

		beego.NSNamespace("/user",
			beego.NSInclude(
				&controllers.UserController{},
			),
		),
		beego.NSNamespace("/work",
			beego.NSInclude(
				&controllers.WorkController{},
			),
		),
		beego.NSNamespace("/active",
			beego.NSInclude(
				&controllers.ActiveController{},
			),
		),
	)
	beego.AddNamespace(ns)
}

////add filter
func jwtAuth(ctx *context.Context) {

	var ret models.Response

	url := ctx.Input.URL()
	beego.Debug(url)

	if url == "/v1/user/login" || url == "/v1/work/addwork" { //登录接口不做jwt验证
		return
	}

	tokenString := ctx.Input.Header("Authorization")

	authResult, err := models.CheckToken(tokenString)

	if err != nil { //出错了
		ret.Code = err.Errcode
		ret.Msg = err.Errmsg
		ctx.Output.JSON(ret, false, false)
		return
	} else if authResult { //验证通过
		return
	}
}
